<?php
// +----------------------------------------------------------------------
// | PublicAction.class.php - MyPT
// +----------------------------------------------------------------------
// | Copyleft (c) 2010 By Asxzy All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Asxzy <asxzy@163.com>
// +----------------------------------------------------------------------
class PublicAction extends CommonAction{
	// 首页跳转
	public function index(){
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->display();
		}else{
			$this->redirect('__APP__');
		}
	}
	
	// 登录页面	
	public function login(){	
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->display();
		}else{
			$this->assign("jumpUrl",'__APP__');
        	$this->error('你已经登录过了,请不要重复登陆');
		}
	}
	
	// 登录验证
	public function checklogin(){
		// 检查验证码
		if($_SESSION['verify'] != md5($_POST['verify'])) {
			$this->error('验证码错误！');
		}
		//生成认证条件
        $map = array();
		// 支持使用绑定帐号登录
		$map['username'] = $_POST['username'];
		$map['password'] = md5($_POST['password']);
		if($_SESSION['verify'] != md5($_POST['verify'])) {
			$this->error('验证码错误！');
		}
		import('@.ORG.RBAC');
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if(!isset($authInfo)) {
            $this->error('用户名密码错误');
        }else{
        	// 将用户信息写入SESSION
            $_SESSION[C('USER_AUTH_KEY')] = $authInfo['id'];
            if(empty($authInfo['nickname'])) $_SESSION['username'] = ($authInfo['username']);
            else $_SESSION['username'] = ($authInfo['nickname']);
            $_SESSION['userid'] = $authInfo['id'];
            $_SESSION['status'] = $authInfo['status'];
            $_SESSION['passkey'] = $authInfo['passkey'];
            $_SESSION['uploaded'] = mksize($authInfo['uploaded']);
            $_SESSION['downloaded'] = mksize($authInfo['downloaded']);
            $_SESSION['share'] = number_format($authInfo['uploaded']/$authInfo['downloaded'],3);
            //保存登录信息
			$User = M('User');
            $data = array();
			$data['id'] = $authInfo['id'];
			$data['last_login'] = get_time();
			$data['login_count'] = array('exp','login_count+1');
			$data['ip'] = get_client_ip();
	    	if(!$User->save($data)){
	    		$this->error('登录日志写入错误');
	    	}
			// 缓存访问权限
            RBAC::saveAccessList();
            $this->assign("jumpUrl",'__APP__');
			$this->success('登录成功！');
		}
	}
	
	// 退出登录
    public function logout()
    {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();
            $this->assign("jumpUrl",'__APP__');
            $this->success('登出成功！');
        }else{
            $this->assign("jumpUrl",'__APP__/Public/login/');
        	$this->error('你还未登录！');
        }
    }
    
    // 注册用户
    public function reg(){
		if(empty($_POST)){
			$this->display();
		}else{
			// 检查验证码
			if($_SESSION['verify'] != md5($_POST['verify'])) {
				$this->error('验证码错误！');
			}
			$user = D('User');
	    	$data = $user->create();
	    	$data['passkey'] = md5($data['username'].time());
			if ($data){
				$this->error($user->getError());			
			}else{
				$role_user = M('role_user');
				if(C('REGIST_EMAIL_CHECK')==false){
					$data['status'] = 'confirmed';
				}else{
					$data['stauts'] = 'pending';
				}
				$access['user_id'] = $user->add($data);
				$access['role_id'] = C('USER_DEFAULT_CLASS');
				if($access['user_id']){
					if($role_user->add($access)){
						if($this->emailcheck($data))
							$this->success('注册成功');
						else $this->error('注册确认邮件发送失败,请联系管理员手动激活帐号');
					}else
						$user->where('id='.$access['user_id'])->delete(); 
				}else{
					$this->error('注册失败');
				}
			}
		}
    }
	
	// 生成验证码
	public function verify(){
		import('ORG.Util.Image');
		Image::buildImageVerify();
	}
	
	// 发送验证码
	public function emailCheck($data = null){
		$this->assign("jumpUrl",'__APP__');
		$ac = false;
		if (empty($data)){
			$ac = true;
			if (!isset($_SESSION[C('USER_AUTH_KEY')])){
				$this->error('非法操作');
			}
			$userid = $_SESSION['userid'];
			$user = M('user');
			$data = $user->find($userid);
		}
		$passkey = $data['passkey'];
		$email = $data['email'];
		$username = $data["username"];
		$address = C('SITE_URL')."/Public/checkBack/passkey/$passkey";
		
		$subject = "亲爱的".$username.",请激活您在".C('SITE_NAME')."注册的帐号";
		$message = "亲爱的".$username."我们已经收到了您在<strong>".C('SITE_NAME')."</strong>的注册信息,请您复制并打开下边的链接来帐号您的帐号.\n确认链接: <a href=\"$address\">".$address."</a><br/>这是一条系统信息,请勿回复,谢谢";
		
		import('@.Email.Email');
		$result = sendemail("亲爱的".$username,$email,$subject,'如果你看到这条信息,请你使用支持html视图的邮件接收器查看该邮件',$message);
		if ($result === true ){
			if ($ac === true)
				$this->success('Email发送成功');
			else return true;
		}else{
			if ($ac === false)
				$this->error('Email发送失败:'.$result);
			else return false;
		}
	}
	
	// 邮箱验证
	public function checkBack(){
		$this->assign("jumpUrl",'__APP__');
		if (!isset($_GET['passkey']))
			$this->error('非法操作');
		$user = M('user');
		$data = $user->where("passkey='".$_GET['passkey']."'")->find();
		if (!$data)
			$this->error('帐号激活失败,请确认激活码的正确性,或者重新获取激活码');
		if($data['status'] != 'pending') $this->error('您的帐号已经激活,请不要重复操作');
		$data2['id'] = $data['id'];
		$data2['status'] = 'confirmed';
		if ($user->save($data2)){
			$this->success('帐号激活成功,欢迎加入'.C('SITE_NAME'));
		}else{
			$this->error('帐号激活失败,请重试');
		}
	}
	
	// 找回密码
	public function getLostPwd(){
		if(empty($_POST)) $this->display();
		$user = M('user');
		$data = $user->where("username='".$_POST['username']."'")->find();
		if (!$data) $this->error('不存在该用户');
		$secret = md5($data['passkey'].time());
		if(!$user->where('id='.$data['id'])->setField(secret,$secret)) $this->error('系统错误,请联系管理员');
		$email = $data['email'];
		$username = $data["username"];
		$address = C('SITE_URL')."/Public/changePwd/secret/$secret";

		$subject = "亲爱的".$username.",确认您在".C('SITE_NAME')."的找回密码请求";
		$message = "亲爱的".$username."我们已经收到了您在<strong>".C('SITE_NAME')."</strong>的找回密码请求,请您复制并打开下边的链接来修改您的密码.谢谢\n确认链接: <a href=\"$address\">".$address."</a><br/>这是一条系统信息,请勿回复,谢谢";
		
		import('@.Email.Email');
		$result = sendemail("亲爱的".$username,$email,$subject,'如果你看到这条信息,请你使用支持html视图的邮件接收器查看该邮件',$message);
		if ($result === true ){
				$this->success('Email发送成功');
		}else{
			$this->error('Email发送失败:'.$result);
		}
	}
	
	// 修改密码
	public function changePwd(){
		if(isset($_POST['password'])){
			// 检查验证码
			if($_SESSION['verify'] != md5($_POST['verify'])) {
				$this->error('验证码错误！');
			}
			if ($_POST['password1'] != $_POST['password2'])  $this->error('两次新密码不同,请重新输入');
			$user = M('user');
			if ($_POST['password'] != $_SESSION['secret']){
				$data = $user->find($_SESSION['userid']);
				if ($data['password'] != md5($_POST['password'])) $this->error('旧密码错误,修改失败');
				if ($data['password'] === md5($_POST['password1'])) $this->error('新旧密码一样,修改失败');
			}else{
				$data = $user->where("secret='".$_SESSION['secret']."'")->find();
				if ($data['password'] === md5($_POST['password1'])) $this->error('新旧密码一样,修改失败');
			}
			if($user->where('id='.$_SESSION['userid'])->setField('password',md5($_POST['password1']))){
				$this->assign("jumpUrl",'__APP__');
				$this->success('修改成功');
			}
			else $this->error('修改失败,');
		}elseif(isset($_GET['secret'])){
			$user = M('user');
			$data = $user->find($_GET['secret']);
			if($data) $this->error('secret错误,请返回.');
			$_SESSION['secret'] = $_GET['secret'];
			$this->assign('password',$_GET['secret']);
			$this->display('changePwd2');
		}else $this->display();
	}

}
?>